/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Animated,
    Platform,
    TouchableWithoutFeedback,
    InteractionManager
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import GoodsItem from '../components/GoodsItem';
import BaiduMap from './BaiduMap';
import SelectCity from '../components/SelectCity';
import ImageCropPicker from 'react-native-image-crop-picker';
import shopService from '../lib/services/shopService';
import StorageUser from '../lib/plugins/StorageUser';
import LoadingModal from '../components/LoadingModal';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class AddStore extends Component{
    constructor(props) {
        super(props);
        var $this = this;
        this.token = '';
        this.state = {
            showStaturs:'',
            modalVisible:false,
            statursList:['个体商户','企业商户'],
            areaList:['狗粮','猫粮','其他'],
            statursName:'未选择',//商户类型
            cityText:'未选择',//所在城市
            location:'未选择',//位置
            shopAddress:'',//详细地址
            shopName:'',//店铺名称
            shopArea:'未选择',//经营范围
            userName:'',//企业联系人
            mobile:'',//联系电话
            IDNumber:'',//身份证号
            businessMobile:'',//客服电话
            userId:this.props.navigation.state.params.userId,//用户ID
            outdoorList:[],//店铺门脸图列表
            outdoorDataList:[],
            outdoorText:'',
            environmentList:[],//店铺环境图列表
            environmentDataList:[],
            environmentText:'',
            licenseList:[],//营业执照图列表
            licenseDataList:[],
            licenseText:'',
            IDList:[],//身份证图列表
            IDDataList:[],
            IDText:'',
            shopInfo:'',//店铺介绍
            licenseNum:'',//营业执照号码
            mapId:'',//地图店铺ID
            load:false
        };
        
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }               
            }).catch(err=> {
                console.log(err)
            });
    }
    // 模态框
    renderNameModal(){
        var list = [];
        if(this.state.showStaturs=='商户类型'){
            list = this.state.statursList;
        }else if(this.state.showStaturs=='经营范围'){
            list = this.state.areaList;
        }
        return(
            <Modal
                transparent={true}
                visible={this.state.modalVisible}
                onRequestClose={()=>this.requestClose()}>
                <TouchableWithoutFeedback onPress={()=>this.setState({modalVisible:false})}>
                    <View style={styles.modalBox}>
                        <View style={styles.listBorder}>
                            {this.renderModalList(list)}
                        </View>
                    </View>
                </TouchableWithoutFeedback>
            </Modal>
        )
    }
    // 渲染模态框内的列表
    renderModalList(list){
        return(
            list.map((item,i)=>{
                return(
                    <TouchableOpacity key={i} onPress={()=>this.changeName(item)}>
                        <View style={styles.listItem}>
                            <Text>{item}</Text>
                        </View>
                    </TouchableOpacity>
                )
            })
            
        )
    }
    render(){
        return (
            <View style={styles.container}>
                {this.renderNameModal()}
                <NavigationBar 
                    leftPress={()=>this.goBack()}
                    leftIcon={'left'} 
                    titleText={'添加店铺'}/>
                <LoadingModal visible={this.state.load} onRequestClose={()=>{console.log('666')}}/>
                <ScrollView>
                    <View style={{height:30,paddingLeft:10,justifyContent:'center'}}>
                        <Text style={{color:'#FF0101'}}>*必填项</Text>
                    </View>
                    <View style={styles.itemBox}>
                        <TouchableOpacity onPress={()=>this._goSelectCity()}>
                            <GoodsItem style={styles.itemBorder} title={'所在城市'} name={this.state.cityText}/>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={()=>this.goBaiduMap()}>
                            <GoodsItem style={styles.itemBorder} title={'位置'} name={this.state.location.address}/>
                        </TouchableOpacity>
                        
                        <GoodsItem onChangeText={(text)=>this.getShopAddress(text)} title={'详细地址'} hasInput={true} placeholder={'xx区xx路xx号'}/>
                    </View>
                    <View style={[styles.itemBox,{marginTop:20}]}>
                        <GoodsItem onChangeText={(text)=>this.getShopName(text)} style={styles.itemBorder} title={'商户名称'} hasInput={true} placeholder={'商户或店铺名称'}/>
                        <TouchableOpacity onPress={()=>this.choseStaturs('商户类型')}>
                            <GoodsItem style={styles.itemBorder} title={'商户类型'} name={this.state.statursName}/>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={()=>this.choseStaturs('经营范围')}>
                            <GoodsItem style={styles.itemBorder} title={'经营范围'} name={this.state.shopArea}/>
                        </TouchableOpacity>
                        <GoodsItem onChangeText={(text)=>this.getUserName(text)} style={styles.itemBorder} title={'企业联系人'} hasInput={true} placeholder={'填写联系人'}/>
                        <GoodsItem onChangeText={(text)=>this.getMobile(text)} style={styles.itemBorder} title={'联系电话'} hasInput={true} placeholder={'填写联系电话'}/>
                        <GoodsItem onChangeText={(text)=>this.getIDNumber(text)} style={styles.itemBorder} title={'身份证号码'} hasInput={true} placeholder={'填写身份证号码'}/>
                        <GoodsItem onChangeText={(text)=>this.getBusinessMobile(text)} style={styles.itemBorder} title={'客服电话'} hasInput={true} placeholder={'填写客服电话'}/>
                        <GoodsItem onChangeText={(text)=>this.getLicenseNum(text)} style={styles.itemBorder} title={'营业执照号'} hasInput={true} placeholder={'填写营业执照号码'}/>
                        <ImageItem that={this} style={styles.itemBorder} title={'店铺门脸图'} data={this.state.outdoorList} onPress={()=>this.choseImg('outdoorList')} staturs={'outdoorList'}/>
                        <ImageItem that={this} data={this.state.environmentList} onPress={()=>this.choseImg('environmentList')} style={styles.itemBorder} staturs={'environmentList'} title={'店内环境图(最多添加9张)'}/>
                        <View>
                            <View style={{flexDirection:'row',height:30,alignItems:'center'}}>
                                <Text style={{color:'#FF1717'}}>*</Text>
                                <Text>店面介绍</Text>
                            </View>
                            <View>
                                <TextInput
                                    style={{padding:3}}
                                    underlineColorAndroid={'transparent'}
                                    textAlignVertical={'top'}
                                    multiline={true}
                                    numberOfLines={7}
                                    onChangeText={(text)=>this.getShopInfo(text)}/>
                            </View>
                        </View>
                    </View>
                    <View style={[styles.itemBox,{marginTop:20}]}>
                        <ImageItem that={this} data={this.state.licenseList} onPress={()=>this.choseImg('licenseList')} style={styles.itemBorder} staturs={'licenseList'} title={'营业执照'}/>
                        <ImageItem that={this} data={this.state.IDList} onPress={()=>this.choseImg('IDList')} staturs={'IDList'} text={'正面'} style={styles.itemBorder} title={'身份证照片'}/>
                    </View>
                    <View style={{marginBottom:20}}>
                        <View style={{height:40,justifyContent:'center',alignItems:'center'}}>
                            <Text style={styles.textColor}>注 : 为了便于审核,以上信息需要您如实填写</Text>
                        </View>
                        <View style={{alignItems:'center'}}>
                            <TouchableOpacity onPress={()=>this.addShopData()} style={{width:3*width/4}}>
                                <View style={{height:40,justifyContent:'center',width:3*width/4,alignItems:'center',backgroundColor:'rgb(79,145,237)',borderRadius:3}}>
                                    <Text style={{color:'#fff'}}>添加店铺</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                    
                </ScrollView>
            </View>
        )

    }
    
    // 返回按钮点击事件
    goBack(){
        this.props.navigation.goBack();
    }
    // 选择图片
    choseImg(name){
        var $this = this;
        if(name=='outdoorList' && this.state.outdoorList.length==1){
            return;
        }else if(name=='environmentList' &&this.state.environmentList.length>=9){
            return;
        }else if(name=='licenseList' && this.state.licenseList.length==1){
            return;
        }else if(name=='IDList' && this.state.IDList.length==1){
            return;
        }
        if(name=='environmentList'){
            ImageCropPicker.openPicker({
                    multiple: true,
                    maxFiles:9,
                    mediaType:'photo',
                }).then(images => {
                    var len = images.length;
                    var arr = [];
                    for(var i=0;i<len;i++){
                        var source = {};
                        if (Platform.OS === 'android') {
                            source = {path: images[i].path, isStatic: true};
                            arr.push(source);
                        } else {
                            source = {path: images[i].path.replace('file://', ''), isStatic: true};
                            arr.push(source);
                        }
                    }
                    var list = $this.state.environmentList;
                    var arrList = $this.state.environmentDataList;
                    list = list.concat(arr);
                    arrList = arrList.concat(images);
                    if(list.length>9){
                        list.splice(9);
                        arrList.splice(9);
                    }
                    $this.setState({
                        environmentList : list,
                        environmentDataList : arrList,
                    });
                    
                }).catch((err)=>{
                    console.log(err)
                })
        }else{
            ImageCropPicker.openPicker({
                    width: 300, 
                    height: 300, 
                    cropping: true,
                    mediaType:'photo',
                }).then(image => { 
                    var source;
                    if (Platform.OS === 'android') {
                        source = {path: image.path, isStatic: true};
                    } else {
                        source = {path: image.path.replace('file://', ''), isStatic: true};
                    }
                    if(name=='outdoorList'){
                        var list = $this.state.outdoorList;
                        var arr = $this.state.outdoorDataList;
                        list.push(source);
                        arr.push(image);
                        $this.setState({
                            outdoorList : list,
                            outdoorDataList : arr,
                        });
                    }else if(name=='licenseList'){
                        var list = $this.state.licenseList;
                        var arr = $this.state.licenseDataList;
                        list.push(source);
                        arr.push(image);
                        $this.setState({
                            licenseList : list,
                            licenseDataList : arr,
                        });
                        
                    }else if(name=='IDList'){
                        var list = $this.state.IDList;
                        var arr = $this.state.IDDataList;
                        list.push(source);
                        arr.push(image);
                        $this.setState({
                            IDList : list,
                            IDDataList : arr,
                        });
                        
                    }
                }).catch((err)=>{
                    console.log(err)
                })
        }                  
    }
    // 跳转到百度地图
    goBaiduMap(){
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('BaiduMap',{getLocation:(data)=>{
            alert(JSON.stringify(data))
            $this.setState({
                location:data
            })
        }})
    }
    // 跳转到选择城市页面
    _goSelectCity() {
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('SelectCity',{getAddress:(data)=>{
            $this.setState({
                cityText:data.province+data.city+data.area
            })
        }})
    }
    // 模态框列表点击事件
    changeName(name){
        if(this.state.showStaturs=='商户类型'){
            this.setState({
                statursName:name,
                modalVisible:false
            })
        }else if(this.state.showStaturs=='经营范围'){
            this.setState({
                shopArea:name,
                modalVisible:false
            })
        }
        
    }
    // 显示模态框
    choseStaturs(staturs){
        this.setState({
            showStaturs:staturs,
            modalVisible:true
        })
    }
    getShopAddress(text){
        this.setState({
            shopAddress:text
        })
    }
    getShopName(text){
        this.setState({
            shopName:text
        })
    }
    getUserName(text){
        this.setState({
            userName:text
        })
    }
    getMobile(text){
        this.setState({
            mobile:text
        })
    }
    getIDNumber(text){
        this.setState({
            IDNumber:text
        })
    }
    getBusinessMobile(text){
        this.setState({
            businessMobile:text
        })
    }
    getShopInfo(text){
        this.setState({
            shopInfo:text
        })
    }
    getLicenseNum(text){
        this.setState({
            licenseNum:text
        })
    }
    addShopData(){
        var $this = this;
        // statursName:'未选择',//商户类型
        // cityText:'未选择',//所在城市
        // location:'未选择',//位置
        // shopAddress:'',//详细地址
        // shopName:'商户或店铺名称',//店铺名称
        // shopArea:'',//经营范围
        // userName:'',//企业联系人
        // mobile:'',//联系电话
        // IDNumber:'',//身份证号
        // businessMobile:'',//客服电话
        // userId:'',//用户ID
        // outdoorList:[],//店铺门脸图列表
        // environmentList:[],//店铺环境图列表
        // licenseList:[],//营业执照图列表
        // IDList:[],//身份证图列表
        // shopInfo:'',//店铺介绍
        var imgArr = [];
        if(this.state.cityText=='未选择'){
            alert('请添选择所在城市！');
            return;
        }else if(this.state.location=='未选择'){
            alert('请添选择位置！');
            return;
        }else if(this.state.shopAddress==''){
            alert('请添填写详细地址！');
            return;
        }else if(this.state.shopName==''){
            alert('请添选择商户名称！');
            return;
        }else if(this.state.statursName=='未选择'){
            alert('请添选择商户类型！');
            return;
        }else if(this.state.shopArea=='未选择'){
            alert('请添选择经营范围！');
            return;
        }else if(this.state.userName==''){
            alert('请添填写企业联系人！');
            return;
        }else if(this.state.mobile==''||(!/^1[3578][0-9]{9}$/.test(this.state.phone))){
            alert('请添填写正确的联系电话！');
            return;
        }else if(this.state.IDNumber==''||(!/\d{18}/.test(this.state.IDNumber))){
            alert('请填写正确的身份证号码！');
            return;
        }else if(this.state.businessMobile==''){
            alert('请添填写客服电话！');
            return;
        }else if(this.state.licenseNum==''){
            alert('请添填写营业执照号！');
            return;
        }else if(this.state.outdoorList.length<1){
            alert('请添加店铺门脸图！');
            return;
        }else if(this.state.environmentList.length<1){
            alert('请添加店铺环境图！');
            return;
        }else if(this.state.shopInfo==''){
            alert('请添填写店面介绍！');
            return;
        }else if(this.state.licenseList.length<1){
            alert('请添加营业执照图！');
            return;
        }else if(this.state.IDList.length<1){
            alert('请添加身份证照片！');
            return;
        }
        var imgArr = [];
        imgArr['front'] = this.state.outdoorDataList[0].path;
        imgArr['license_one'] = this.state.licenseDataList[0].path;
        imgArr['id_card_img'] = this.state.IDDataList[0].path;

        var shopArr = [];
        var list = this.state.environmentDataList;
        var len = list.length;
        for(var i=0;i<len;i++){
            shopArr['img'+(i+1)] = list[i].path;
        }
        this.setState({
            load:true,
        })
        shopService.upFile(function(data){
            if(data.code==10000){
                shopService.addShop(function(result){
                    alert(JSON.stringify(data));
                    if(result.code==10000){
                        $this.setState({
                            load:false
                        })
                        Alert.alert(
                            '提示信息',
                            '添加成功',
                            [{text: '确定', onPress: () => {
                                $this.props.navigation.state.params.upData();
                                $this.goBack();
                            }}])
                    }
                },$this.state.cityText,
                  $this.state.location.address,
                  $this.state.shopAddress,
                  $this.state.shopName,
                  $this.state.statursName,
                  $this.state.shopArea,
                  $this.state.userName,
                  $this.state.mobile,
                  $this.state.businessMobile,
                  $this.state.userId,
                  $this.state.IDNumber,
                  $this.state.licenseNum/*营业执照号码*/,
                  $this.state.location.uid/*百度地图店铺ID*/,
                  $this.state.location.lng,
                  $this.state.location.lat,
                  $this.state.shopInfo,
                  data.data,
                  imgArr,
                  $this.token)
            }
        },imgArr,$this.token)


        
        
    }
}

class ImageItem extends Component{
    showImages(){
        var list = this.props.data;
        if(list && list.length>0){
            return(
                list.map((item,i)=>{
                    if(i<9){
                        return(
                            <View key={i} style={{paddingRight:10}}>
                                <TouchableOpacity style={{paddingTop:10,paddingRight:10}} onPress={()=>this.selectItem(i)}>
                                    <ImageWrapper style={{width:20,height:20,position:'absolute',top:0,right:0,zIndex:1000}} icon={'stop'}/>
                                    <Image style={{width:60,height:60}} source={{uri:item.path}}/>               
                                </TouchableOpacity>
                                
                            </View>
                        )
                    }
                })
            )
        }else{
            return; 
        }
        
    }

    selectItem(key){
        var that = this.props.that;
        var staturs = this.props.staturs;
        
        // alert(JSON.stringify(that.state.outdoorList))
        if(staturs=='outdoorList'){
            var list = [];
            list = that.state.outdoorList;
            list.splice(key,1);
            that.setState({
                outdoorList:list
            })
        }else if(staturs=='environmentList'){
            var list = [];
            list = that.state.environmentList;
            list.splice(key,1);
            that.setState({
                environmentList:list
            })
        }else if(staturs=='licenseList'){
            var list = [];
            list = that.state.licenseList;
            list.splice(key,1);
            that.setState({
                licenseList:list
            })
        }else if(staturs=='IDList'){
            var list = [];
            list = that.state.IDList;
            list.splice(key,1);
            that.setState({
                IDList:list
            })
        }
        
    }

    render(){
        return(
            <View style={this.props.style}>
                <View style={{flexDirection:'row',height:30,alignItems:'center'}}>
                    <Text style={styles.textColor}>*{this.props.text}</Text>
                    <Text>{this.props.title}</Text>
                </View>
                <View style={{width:width,padding:10,flexDirection:'row',flexWrap:'wrap'}}>
                    {this.showImages()}
                    <TouchableOpacity onPress={this.props.onPress}>
                        <ImageWrapper style={{marginTop:10}} width={60} height={60} icon={'addImg'}/>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }
}


const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    }, 
    itemBorder:{
        borderBottomWidth:1,
        borderBottomColor:'#DFDFE2'
    },
    itemBox:{
        borderBottomWidth:1,
        borderBottomColor:'#DFDFE2',
        borderTopWidth:1,
        borderTopColor:'#DFDFE2',
        paddingLeft:10,
        backgroundColor:'#fff'
    },
    textColor:{
        color:'#FF1717'
    },
    modalBox:{
        flex:1,
        backgroundColor:'rgba(3,3,3,.2)',
        justifyContent:'center',
        alignItems:'center',
    },
    listItem:{
        width:3*width/4,
        height:40,
        justifyContent:'center',
        backgroundColor:'#fff',
        paddingLeft:10,
    },
    
});